package com.jacky.ws.handler;

import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SocketIOEventHandler {

    private final Logger LOG = LoggerFactory.getLogger(SocketIOEventHandler.class);

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        LOG.info("客户端断开连接:{}", client.getSessionId());
        client.disconnect();
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        HandshakeData data = client.getHandshakeData();
        String room = data.getSingleUrlParam("room");
        String userId = data.getSingleUrlParam("userId");

        SocketIONamespace namespace = client.getNamespace();
        Transport transport = client.getTransport();
        String ns = namespace == null ? "" : namespace.getName();
        String tp = transport == null ? "" : transport.getValue();
        client.joinRoom(room);
        LOG.info("客户端[{}],namespace:{},transport:{}.userId:{},url:{} 连接成功", room, ns, tp, userId, data.getUrl());
    }

    @OnEvent(value = "msg_event")
    public void onMessage(SocketIOClient client, AckRequest ackRequest, String data) {
        LOG.info("事件[{}],收到消息:{},nameSpace:{}", "msg_event", data, client.getNamespace().getName());

        client.sendEvent("msg_event", "收到消息,内容为:" + data);
    }

}
